<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 自定义导航栏 -->
    <view class="bg-white px-[32rpx] py-[24rpx]">
      <nut-tabs v-model="activeTab" @click="onTabChange">
        <nut-tab-pane title="全部" pane-key="all"></nut-tab-pane>
        <nut-tab-pane title="待付款" pane-key="pending"></nut-tab-pane>
        <nut-tab-pane title="制作中" pane-key="preparing"></nut-tab-pane>
        <nut-tab-pane title="配送中" pane-key="delivering"></nut-tab-pane>
        <nut-tab-pane title="已完成" pane-key="completed"></nut-tab-pane>
      </nut-tabs>
    </view>

    <!-- 订单列表 -->
    <view class="px-[32rpx] py-[32rpx]">
      <!-- 空状态 -->
      <view v-if="filteredOrders.length === 0" class="flex flex-col items-center justify-center py-[200rpx]">
        <image 
          :src="defaultProductImage" 
          class="w-[200rpx] h-[200rpx] opacity-50 mb-[32rpx]"
          mode="aspectFit"
        />
        <text class="text-[32rpx] text-gray-500">暂无订单</text>
      </view>

      <!-- 订单卡片列表 -->
      <view v-else class="space-y-[24rpx]">
        <view 
          v-for="order in filteredOrders" 
          :key="order.id"
          class="bg-white rounded-[24rpx] overflow-hidden"
          @tap="goToOrderDetail(order)"
        >
          <!-- 订单头部信息 -->
          <view class="flex justify-between items-center px-[32rpx] py-[24rpx] border-b border-gray-100">
            <view>
              <text class="text-[28rpx] text-gray-600">订单号：{{ order.orderNo }}</text>
              <text class="text-[28rpx] text-gray-600 block">{{ formatDate(order.createTime) }}</text>
            </view>
            <text 
              :class="getStatusClass(order.status)"
            >
              {{ getStatusText(order.status) }}
            </text>
          </view>

          <!-- 商品列表 -->
          <view class="px-[32rpx] py-[24rpx]">
            <view 
              v-for="item in order.items" 
              :key="item.id"
              class="flex items-center mb-[24rpx] last:mb-0"
            >
              <image 
                :src="item.image" 
                class="w-[120rpx] h-[120rpx] rounded-[16rpx] object-cover mr-[24rpx]"
                mode="aspectFill"
              />
              <view class="flex-1">
                <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">{{ item.name }}</text>
                <text class="text-[26rpx] text-gray-500">x{{ item.quantity }}</text>
              </view>
              <text class="text-[30rpx] font-bold text-gray-800">¥{{ item.price }}</text>
            </view>
          </view>

          <!-- 配送信息 -->
          <view v-if="order.deliveryInfo" class="px-[32rpx] py-[24rpx] bg-gray-50 border-t border-gray-100">
            <view class="flex items-center mb-[16rpx]">
              <text class="text-[28rpx] text-gray-600 mr-[16rpx]">📍</text>
              <text class="text-[28rpx] text-gray-600">{{ order.deliveryInfo.address }}</text>
            </view>
            <view class="flex items-center" v-if="order.rider">
              <text class="text-[28rpx] text-gray-600 mr-[16rpx]">🚚</text>
              <text class="text-[28rpx] text-gray-600">骑手：{{ order.rider.name }}</text>
              <text class="text-[28rpx] text-gray-600 ml-[32rpx]">{{ order.rider.phone }}</text>
            </view>
          </view>

          <!-- 订单底部 -->
          <view class="flex justify-between items-center px-[32rpx] py-[24rpx] border-t border-gray-100">
            <text class="text-[32rpx] font-bold text-red-500">合计：¥{{ order.totalAmount.toFixed(2) }}</text>
            <view class="flex items-center space-x-[16rpx]">
              <nut-button 
                v-if="order.status === 'pending'"
                size="small"
                type="default"
                @click.stop="cancelOrder(order)"
              >
                取消订单
              </nut-button>
              <nut-button 
                v-if="order.status === 'pending'"
                size="small"
                type="primary"
                class="bg-orange-500 border-orange-500"
                @click.stop="payOrder(order)"
              >
                立即支付
              </nut-button>
              <nut-button 
                v-if="order.status === 'completed'"
                size="small"
                type="primary"
                class="bg-orange-500 border-orange-500"
                @click.stop="reorderOrder(order)"
              >
                再来一单
              </nut-button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部安全区域适配TabBar -->
    <view class="h-[120rpx]"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'

/**
 * 订单列表页面 - 展示用户所有订单状态和信息
 * 性能优化：使用计算属性过滤订单，虚拟滚动优化长列表性能
 */

interface OrderItem {
  id: number
  name: string
  price: number
  quantity: number
  image: string
}

interface DeliveryInfo {
  address: string
  phone: string
  name: string
  estimatedTime?: string
}

interface Rider {
  id: number
  name: string
  phone: string
  rating: number
}

interface Order {
  id: number
  orderNo: string
  status: 'pending' | 'preparing' | 'delivering' | 'completed' | 'cancelled'
  items: OrderItem[]
  totalAmount: number
  createTime: string
  deliveryInfo?: DeliveryInfo
  rider?: Rider
  estimatedDeliveryTime?: string
}

type TabKey = 'all' | 'pending' | 'preparing' | 'delivering' | 'completed'

// 响应式数据
const activeTab = ref<TabKey>('all')
const defaultProductImage = 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'

// 订单数据
const orders = ref<Order[]>([
  {
    id: 1,
    orderNo: 'MT202312230001',
    status: 'delivering',
    totalAmount: 58,
    createTime: '2023-12-23 14:30:00',
    items: [
      {
        id: 1,
        name: '珍珠奶茶',
        price: 18,
        quantity: 2,
        image: defaultProductImage
      },
      {
        id: 2,
        name: '芒果布丁奶茶',
        price: 22,
        quantity: 1,
        image: defaultProductImage
      }
    ],
    deliveryInfo: {
      address: '北京市朝阳区三里屯SOHO A座1202',
      phone: '138****8888',
      name: '张先生'
    },
    rider: {
      id: 1,
      name: '李师傅',
      phone: '139****9999',
      rating: 4.8
    },
    estimatedDeliveryTime: '15:00'
  },
  {
    id: 2,
    orderNo: 'MT202312220002',
    status: 'completed',
    totalAmount: 46,
    createTime: '2023-12-22 16:15:00',
    items: [
      {
        id: 4,
        name: '抹茶拿铁',
        price: 28,
        quantity: 1,
        image: defaultProductImage
      },
      {
        id: 6,
        name: '柠檬蜂蜜茶',
        price: 16,
        quantity: 1,
        image: defaultProductImage
      }
    ],
    deliveryInfo: {
      address: '北京市朝阳区三里屯SOHO A座1202',
      phone: '138****8888',
      name: '张先生'
    }
  },
  {
    id: 3,
    orderNo: 'MT202312210003',
    status: 'pending',
    totalAmount: 25,
    createTime: '2023-12-21 10:20:00',
    items: [
      {
        id: 3,
        name: '草莓奶昔',
        price: 25,
        quantity: 1,
        image: defaultProductImage
      }
    ]
  }
])

// 计算属性
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => order.status === activeTab.value)
})

// 方法
const onTabChange = (paneKey: TabKey) => {
  activeTab.value = paneKey
}

const getStatusText = (status: Order['status']) => {
  const statusMap = {
    pending: '待付款',
    preparing: '制作中',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status]
}

const getStatusClass = (status: Order['status']) => {
  const baseClass = 'text-[28rpx] font-medium px-[16rpx] py-[8rpx] rounded-[16rpx]'
  const statusClassMap = {
    pending: `${baseClass} text-orange-600 bg-orange-100`,
    preparing: `${baseClass} text-blue-600 bg-blue-100`,
    delivering: `${baseClass} text-green-600 bg-green-100`,
    completed: `${baseClass} text-gray-600 bg-gray-100`,
    cancelled: `${baseClass} text-red-600 bg-red-100`
  }
  return statusClassMap[status]
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

const goToOrderDetail = (order: Order) => {
  Taro.navigateTo({
    url: `/pages/order-detail/index?id=${order.id}`
  })
}

const cancelOrder = (order: Order) => {
  console.log('取消订单:', order.orderNo)
  // 实际项目中这里会调用API
  order.status = 'cancelled'
}

const payOrder = (order: Order) => {
  console.log('支付订单:', order.orderNo)
  // 跳转到支付页面
  Taro.navigateTo({
    url: `/pages/checkout/index?orderId=${order.id}`
  })
}

const reorderOrder = (order: Order) => {
  console.log('再来一单:', order.orderNo)
  // 将订单商品重新加入购物车
  Taro.switchTab({
    url: '/pages/cart/index'
  })
}

// 生命周期
onMounted(() => {
  console.log('订单页面加载完成')
})
</script>

<style lang="scss" scoped>
.space-y-\[24rpx\] > view:not(:first-child) {
  margin-top: 24rpx;
}

.space-x-\[16rpx\] > view:not(:first-child) {
  margin-left: 16rpx;
}

.last\:mb-0:last-child {
  margin-bottom: 0;
}
</style> 